package com.feature50.clarity.formui;

import org.apache.log4j.Logger;

import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.Executors;
import java.io.InputStream;

import com.jformdesigner.model.FormModel;
import com.jformdesigner.runtime.FormCreator;
import com.jformdesigner.runtime.FormLoader;
import com.feature50.clarity.FormException;
import com.feature50.clarity.formui.jfd.FormUIJFormDesigner;
import com.feature50.clarity.formui.jfd.JFormDesignerFormUILoader;

public class FormUIFactory {
    private static final Logger logger = Logger.getLogger(FormUIFactory.class);

    private static FormUIFactory instance;

    private static List<FormUILoader> loaders = new ArrayList<FormUILoader>();
    static {
        loaders.add(new JFormDesignerFormUILoader());
    }

    private FormUIFactory() {}

    /**
     *
     * @param key
     * @return
     * @throws FormException
     */
    public FormUI getFormUI(final String key) throws FormException {
        return loadFormUI(key);
    }

    /**
     *
     * @param key
     * @return
     * @throws com.feature50.clarity.FormException
     */
    private FormUI loadFormUI(String key) throws FormException {
        FormUI formUI = null;

        // try to load the form as a JFormDesigner form
        long start = System.currentTimeMillis();
        for (int i = 0; i < loaders.size(); i++) {
            formUI = loaders.get(i).loadFormUI(key);
            if (formUI != null) break;
        }
        logger.debug(String.format("FormUI loaded in %1$d ms", (System.currentTimeMillis() - start)));

        if (formUI == null) {
            String msg = String.format("Couldn't load form '%1$s' with of the %2$d registered FormUILoaders", key, loaders.size());
            logger.error(msg);
            throw new FormException(msg);
        }

        return formUI;
    }

    public void registerLoader(FormUILoader loader) {
        loaders.add(loader);
    }

    public static synchronized FormUIFactory getInstance() {
        if (instance == null) {
            instance = new FormUIFactory();
        }

        return instance;
    }
}